import type { sysAuthToken } from '@/api/auth/type.ts'
import { TOKEN_KEY } from '@/contants'
import { defineStore } from 'pinia'
import { ref } from 'vue'

export const useTokenStore = defineStore('tokenStore', () => {
  //token对象
  const sys_token = ref<sysAuthToken | null>(getToken())
  //token字符串值
  const token_value = ref<string | null>(null)

  // 初始化token_value
  token_value.value = sys_token.value?.token ?? null

  //获取token
  function getToken(): sysAuthToken | null {
    const tokenJSON = localStorage.getItem(TOKEN_KEY.value)
    return tokenJSON ? JSON.parse(tokenJSON) : null
  }

  //设置token
  function setToken(token: sysAuthToken) {
    console.log('token存储开始')
    localStorage.setItem(TOKEN_KEY.value, JSON.stringify(token))
    sys_token.value = token
    token_value.value = token.token
  }

  // 删除 Token
  function removeToken(): void {
    localStorage.removeItem(TOKEN_KEY.value)
  }

  //验证token
  function isExist(): boolean {
    return !!localStorage.getItem(TOKEN_KEY.value)
  }





  return {
    TOKEN_KEY,
    sys_token,
    getToken,
    setToken,
    removeToken,
    isExist,
  }
})
